package com.bowlong.third.grizzly.codec;

import java.io.IOException;
import java.util.Map;

import org.glassfish.grizzly.Buffer;

import com.bowlong.third.grizzly.GrizzlyEx;
import com.bowlong.util.NewMap;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class Message {
	private NewMap map;
	private byte[] body;
	private int length;

	public Message() {
	}

	public Message(Buffer sourceBuffer, int length) throws IOException {
		setMsg(sourceBuffer, length);
	}

	public Message(Map map) {
		map = new NewMap(map);
	}

	public Message(String str) {
		map = new NewMap();
		map.put("str", str);
	}

	public Message(byte[] buf) {
		this.body = buf;
		this.length = buf.length;
	}

	public void setMsg(Buffer sourceBuffer, int length) throws IOException {
		map = GrizzlyEx.readNewMap(sourceBuffer);
		this.length = length;
	}

	public NewMap map() {
		return map;
	}

	public int length() {
		return length;
	}

	public byte[] body() throws IOException {
		if (body != null) {
			length = body.length;
			return body;
		}

		body = GrizzlyEx.writeMap(map);
		length = body.length;
		return body;
	}

	public String toString() {
		return map == null ? "null" : map.toString();
	}

}
